import sys
import win32gui

def activate_window(window_title):
    """激活指定窗口，确保输入能被接收"""
    try:
        hwnd = win32gui.FindWindow(None, window_title)
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
            print(f"✅ 已激活窗口: {window_title}")
        else:
            enum_windows()  # 辅助调试：列出所有窗口
            print(f"❌ 未找到窗口: {window_title}")
            print("🛑 程序终止。请检查游戏是否已启动，或窗口标题是否正确。")
            sys.exit(1)  # 终止程序，返回错误码 1
    except Exception as e:
        print(f"激活窗口失败: {e}")

def enum_windows():
    """枚举所有可见窗口标题"""
    def callback(hwnd, window):
        if win32gui.IsWindowVisible(hwnd):
            text = win32gui.GetWindowText(hwnd)
            if text:
                window.append(text)
        return True
    windows = []
    win32gui.EnumWindows(callback, windows)
    print("当前窗口标题列表：")
    for i,w in enumerate(windows):
        print(f"{i+1}   {w}")